package com.viewplug.listView;


import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;

import com.viewplug.R;

/**
 * Created by mac_wk on 14-10-27.
 */
public class RefreshListView extends ListView implements AbsListView.OnScrollListener {

    private float mLastY = -1;
    private Scroller mScroller;
    private OnScrollListener mScrollListener;
    private OnRefreshListViewListener mRefreshListener;
    private ListViewFooter mFooterView;//头部的view
    private ListViewHeader mHeaderView;//底部的view

    private RelativeLayout mHeaderViewContent;
    //显示时间的view
    private TextView mHeaderTimeView;
    private int mHeaderViewHeight;//headview的高度
    private boolean mEnablePullRefresh = true;//是否允许下拉刷新
    private boolean mPullRefreshing = false;//是否正在刷新中

    private boolean mEnablePullLoad;
    private boolean mPullLoading;
    private boolean mIsFooterReady = false;

    private int mTotalItemCount;//listview的item的数量
    private int mScrollBack;

    private final static int SCROLLBACK_HEADER = 0;
    private final static int SCROLLBACK_FOOTER = 1;

    private final static int SCROLL_DURATION = 400; // scroll back duration
    private final static int PULL_LOAD_MORE_DELTA = 50; // when pull up >= 50px
    public final static int STATE_NORMAL = 0;
    public final static int STATE_READY = 1;
    public final static int STATE_REFRESHING = 2;
    protected final static float OFFSET_RADIO = 1.8f; // support iOS like pull

    private void init(Context context) {
        mScroller = new Scroller(context,new DecelerateInterpolator());
        setOnScrollListener(this);
        //初始化头部
        mHeaderView = new ListViewHeader(context);
        mHeaderViewContent = (RelativeLayout) mHeaderView.findViewById(R.id.viewplug_listview_header_content);
        mHeaderTimeView = (TextView) mHeaderView.findViewById(R.id.viewplug_listview_header_time);
        addHeaderView(mHeaderView);
        //
        // 初始化头部的高度
        mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                mHeaderViewHeight = mHeaderViewContent.getHeight();
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
        //初始化底部
        mFooterView = new ListViewFooter(context);

    }

    //设置是否可以下拉刷新
    public void setPullRefreshEnable(boolean enable)
    {
        mEnablePullRefresh = enable;
        if (!mEnablePullRefresh)
            mHeaderViewContent.setVisibility(View.INVISIBLE);
        else
            mHeaderViewContent.setVisibility(View.VISIBLE);
    }
    //设置是否可以上拉加载
    public void setpullLoadEnable(boolean enable)
    {
        mEnablePullLoad = enable;
        if (!mEnablePullLoad)
        {
            mFooterView.hide();
            mFooterView.setOnClickListener(null);
        }else
        {
            mPullLoading = false;
            mFooterView.show();
            mFooterView.setState(ListViewFooter.STATE_NORMAL);
        }
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        //保证footer是最后一个view，并且只添加一次
        if (mIsFooterReady == false)
        {
            mIsFooterReady = true;
            addFooterView(mFooterView);
        }
        super.setAdapter(adapter);
    }

//    public void stopRefresh()
//    {
//        if (mPullRefreshing == true)
//        {
//            mPullRefreshing = false;
//            resetHeaderHeight();
//        }
//    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            if (mScrollBack == SCROLLBACK_HEADER) {
                mHeaderView.setVisiableHeight(mScroller.getCurrY());
            } else {
                mFooterView.setBottomMargin(mScroller.getCurrY());
            }
            postInvalidate();
        }
        super.computeScroll();
    }
    public void stopLoadMore() {
        if (mPullLoading == true) {
            mPullLoading = false;
            mFooterView.setState(RefreshListView.STATE_NORMAL);
        }
    }

    private void resetFooterHeight() {
        int bottomMargin = mFooterView.getBottomMargin();
        if (bottomMargin > 0) {
            mScrollBack = SCROLLBACK_FOOTER;
            mScroller.startScroll(0, bottomMargin, 0, -bottomMargin,
                    SCROLL_DURATION);
            invalidate();
        }
    }
    private void resetHeaderHeight() {
        int height = mHeaderView.getVisibleHeight();
        //如果高度为0就返回
        if (height == 0)
            return;
        //如果如果正在刷新或者高度小于head的高度也返回
        if(mPullRefreshing && height <= mHeaderViewHeight)
            return;
        int finalHeight = 0;
        //如果正在刷新并且高度大于header高度
        if (mPullRefreshing && height >mHeaderViewHeight)
        {
            finalHeight = mHeaderViewHeight;
        }
        mScrollBack = SCROLLBACK_HEADER;
        mScroller.startScroll(0,height,0,finalHeight-height,SCROLL_DURATION);
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mLastY==-1)
            mLastY = ev.getRawY();
        switch (ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                mLastY = ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float deltaY = ev.getRawY()-mLastY;
                mLastY = ev.getRawY();
                //当可见是第一个选项的时候 并且 head可见高度大于0或者移动距离大于0；
                if (getFirstVisiblePosition()==0&&(mHeaderView.getVisibleHeight()>0||deltaY>0))
                {
                    //开始滑动头部
                    updateHeaderHeight(deltaY / OFFSET_RADIO);
                }
                break;
            default:
                mLastY = -1; // reset
                if (getFirstVisiblePosition() == 0) {
                    // invoke refresh
                    if (mEnablePullRefresh
                            && mHeaderView.getVisibleHeight() > mHeaderViewHeight) {
                        mPullRefreshing = true;
                        mHeaderView.setState(RefreshListView.STATE_REFRESHING);
                        if (mRefreshListener != null) {
                            onFresh();

                        }
                    }
                    resetHeaderHeight();
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    private void onFresh() {

        mRefreshListener.onFreshing();
    }



    public void setOnRefreshListener(OnRefreshListViewListener mRefreshListener) {
        this.mRefreshListener = mRefreshListener;
    }

    public interface  OnRefreshListViewListener{
        public void onFreshing();

        public void onloadData();

    }
    private void updateHeaderHeight(float v) {
        mHeaderView.setVisiableHeight((int) (v+mHeaderView.getVisibleHeight()));
        setSelection(0);

    }

    public void setEnablePullLoad(boolean mEnablePullLoad) {
        this.mEnablePullLoad = mEnablePullLoad;
    }

    public RefreshListView(Context context) {
        super(context);
        init(context);
    }


    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @TargetApi(Build.VERSION_CODES.L)
    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        mTotalItemCount = totalItemCount;
        int now_count = firstVisibleItem+visibleItemCount;
        if(now_count>=totalItemCount)
        {
            if (mRefreshListener!=null)
                mRefreshListener.onloadData();
        }

    }
}
